package com.xiaoliu.dao;

import com.xiaoliu.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ForgetDao {
    Connection con = null;// 连接源
    PreparedStatement ps = null;// 预处理sql语句
    ResultSet rs = null;// 结果集

    /*
     * 查询用户名是否与邮箱匹配
     * */
    public boolean userExists(String username, String email) {
        boolean bo = false;
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("数据库连接成功~");
            String sql = "select * from users where username = ? and email = ?";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, email);
                rs = ps.executeQuery();
                while (rs.next()) {
                    bo = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }
        } else {
            System.out.println("数据库连接失败！");
        }
        return bo;
    }
    /*
     * 如果用户名和邮箱匹配，则可以操作更改密码
     * */
    public boolean change(String user, String pwd, String email) {
        boolean bo = false;
        if (userExists(user,email)) {
            con = JDBCUtil.getCon();
            if (con != null) {
                System.out.println("数据库连接成功~");
                String sql = "update users set pwd = ? where username = ?";
                try {
                    ps = con.prepareStatement(sql);
                    ps.setString(1, pwd);
                    ps.setString(2, user);
                    int affectedRows = ps.executeUpdate();
                    if (affectedRows > 0) {
                        bo = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    JDBCUtil.close(ps, con);
                }
            } else {
                System.out.println("数据库连接失败！");
            }
        }
        return bo;
    }
}
